package com.roc.web.action.operator;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.MerchantModuleRight;
import com.roc.pojo.ModuleCategory;
import com.roc.pojo.Operators;
import com.roc.pojo.PowerModel;
import com.roc.pojo.PowerModule;
import com.roc.service.IMerchantServices;
import com.roc.service.IModelService;
import com.roc.service.IPagenitionService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.OperatorsStatus;
import com.roc.util.constant.Role;
import com.roc.util.constant.SexStatus;

/**
 * 
 * @author 陈锴
 * 
 * 权限管理
 * 
 * 2014-08-06
 *
 */

/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Company: </p>
* @author 
* @date 2016年11月21日下午5:27:05
*/
@Component
@Scope("prototype")
@Namespace("/powers")
public class PowerInfoAction extends PaginationBaseAction{
	
	private Logger logger=LogManager.getLogger(PowerInfoAction.class);
	
	private PowerInfoSearchCondition searchCondition;
	
	private Operators merchant;
	private List<Object> modelRsList = new ArrayList<Object>();
	private PowerModel modelHead;
	private String[] agentList;
	private Map<String, String> roleList=new TreeMap<String,String>();
	@Autowired
	IorgService orgService;
	@Autowired
	IModelService modelService;
	@Autowired
	IPagenitionService pagenitionService;
	
	@Autowired 
	IMerchantServices merchantServices;
	
	@Autowired
	IPowerInfoService powerInfoService;
	
	@Action(value = "queryMerchantYJ", results = { @Result(name = "success", location = "/pages/operator/operator_power.jsp"),@Result(name = "error", location = "/error.jsp")
             })
	public String queryMerchantAction() throws Exception{
		Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(!logingOperators.getRoleType().equals(Role.OPERATORS_COMM.getCode())&&!logingOperators.getRoleType().equals(Role.OPERATORS_LEAD.getCode())&&!logingOperators.getRoleType().equals(Role.SYSTEM.getCode())&&!logingOperators.getRoleType().equals(Role.O_MANAGER.getCode())&&!logingOperators.getRoleType().equals(Role.AGENT.getCode())){
			addActionError("此登陆账号没有权限");
			return ERROR;
		}
		//查询所有的机构
		org();
		
		return SUCCESS;
	}
	
	@Action(value = "queryMerchantListYJ", results = { @Result(name = "success", location = "/pages/operator/operator_power.jsp"),@Result(name = "error", location = "/error.jsp")
           })
	//查询操作员
	public String queryMerchantListAction() throws Exception{
		
        Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		if(searchCondition==null){
			searchCondition=(PowerInfoSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new PowerInfoSearchCondition();
			}
		}
		
		try {
			
			org();
			//this.setCurrentPage(this.checkCurrentPage());
			/*if(Role.AGENT.getCode().equals(logingOperators.getRoleType())){//代理商
				 List<Operators> opList=merchantServices.listAllSubMerchants(logingOperators.getId());
				 agentList= new String[opList.size()];
				 for (int i=0;i<opList.size();i++) {
					 
					Operators o=opList.get(i);
					if(o.getId()!=logingOperators.getId()){
						agentList[i]=Long.toString(o.getId());
					}
					
				}
			   searchCondition.setAgentId(agentList);
			}else if(Role.AGENT_BUSS.getCode().equals(logingOperators.getRoleType())){//业务员
				 agentList= new String[1];
				 agentList[0]=Long.toString(logingOperators.getId());
				 searchCondition.setAgentId(agentList);
			}*/
			searchCondition.setCurrrentOrgCode(logingOperators.getOneagentid());
			searchCondition.setOpId(String.valueOf(logingOperators.getId()));//id
			searchCondition.setCurrrentRoleType(logingOperators.getRoleType());//角色
			int rows=pagenitionService.countSQL(searchCondition);
			searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);

			List<Operators> operatorList= new ArrayList<Operators>();
			if(searchRsList!=null&&searchRsList.size()>0){
				/*Iterator iterator=searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj= (Object[])iterator.next();
					Operators oper=new Operators(); 
					
					oper.setAccountNo(Constance.Null2EmptyTrim(obj[0]));
					oper.setRealName(Constance.Null2EmptyTrim(obj[1]));
					oper.setSex(SexStatus.valueOfCode(Constance.Null2EmptyTrim(obj[2])).getName());
					oper.setMobile(Constance.Null2EmptyTrim(obj[3]));
					oper.setOrgCode(Constance.Null2EmptyTrim(obj[4]));
					oper.setRoleType(Constance.Null2EmptyTrim(obj[5]));
					oper.setCardNo(Constance.Null2EmptyTrim(obj[6]));
					oper.setStatus(OperatorsStatus.valueOfCode(Constance.Null2EmptyTrim(obj[7])).getName());
					oper.setId(Long.parseLong(Constance.Null2EmptyTrim(obj[8])));
					operatorList.add(oper);
				}*/
				Iterator<?> iterator = searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj = (Object[]) iterator.next();
					Operators msb = new Operators();
					msb.setId(Long.parseLong(obj[0].toString()));
					msb.setAccountNo(obj[1].toString());
					msb.setRealName(obj[2].toString());
					msb.setSex(SexStatus.valueOfCode(Constance.Null2EmptyTrim(obj[3])).getName());
					msb.setMobile(obj[4].toString());
					msb.setRoleType(roleList.get(obj[5].toString()));
					//msb.setRoleType(obj[5].toString());
					msb.setCardNo(obj[6].toString());
					msb.setStatus(OperatorsStatus.valueOfCode(Constance.Null2EmptyTrim(obj[7])).getName());
					msb.setOrgCode(obj[8].toString());
					msb.setValidStartDate(obj[9].toString());
					msb.setValidEndDate(obj[10].toString());
					operatorList.add(msb);
				}
			}
			getRequest().setAttribute("operatorList",operatorList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (ServiceException e) {
			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		return SUCCESS;
	}
	/**
	 * 操作员权限信息管理
	 * @Title: queryPowerAction
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 * @author JD
	 * @date: 2017年7月24日 下午1:56:55
	 *
	 */
	@Action(value = "queryPowerYJ", results = { @Result(name = "success", location = "/pages/operator/power_view.jsp")
            })
	//查询权限
	public String queryPowerAction(){
		Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		//查询要赋权限的操作员已经拥有的权限
		List<MerchantModuleRight> moduleList=new ArrayList<MerchantModuleRight>();
		
		//查询当前登录角色可以赋给下级的权限
		List<ModuleCategory> moduleCateList=new ArrayList<ModuleCategory>();
		
		try {
			moduleList=powerInfoService.queryOpertorPowerList(merchant.getAccountNo(),null);
			
			moduleCateList=powerInfoService.queryModuleCategoryList(logingOperators,null);
			merchant=merchantServices.findMerchantByNo(merchant.getAccountNo());
			merchant.setRoleName(ConfigProperties.getRoleType(merchant.getRoleType()));
			merchant.setStatusDesc(OperatorsStatus.valueOfCode(merchant.getStatus()).getName());
			getRequest().setAttribute("moduleList", moduleList);
			getRequest().setAttribute("moduleCateList", moduleCateList);
			getRequest().setAttribute("merchant",merchant);
			getRequest().setAttribute("accountNo", merchant.getAccountNo());
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		
		return SUCCESS;
	}
	
	
	/**
	 * 设置数据分析系统权限
	 * */
	@Action(value = "szAnalyPower", results = { @Result(name = "success", location = "/pages/operator/power_analy_view.jsp"),
			@Result(type="chain", name =INPUT, location = "search")
    })
	public String szAnalyPower(){
       
		Operators oper=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		if(merchant==null || !oper.getRoleType().equals("00") ){
			addActionMessage("请用系统管理员角色选择一个公司内部角色进行权限设置 ");
			return INPUT;
		}
		
		try{
			merchant=merchantServices.findMerchantByNo(merchant.getAccountNo());
			//非清算风控角色/运营  或者特定账号
			if(!merchant.getRoleType().equals(Role.CLEAR_LEAD.getCode()) && !merchant.getRoleType().equals(Role.CLEAR_OPERATORS.getCode()) &&
			   !merchant.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) && !merchant.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())	
			   && merchant.getSuperiorId()!=1   && merchant.getRoleType().equals(Role.OPERATORS_COMM.getCode()) ){
				addActionMessage("请选择一个内部运维账号进行权限设置！");
				return INPUT;
			}
			merchant.setRoleName(ConfigProperties.getRoleType(merchant.getRoleType()));	
			//查询操作员所拥有的权限
			List<MerchantModuleRight> moduleList=new ArrayList<MerchantModuleRight>();
			
			//查询该操作员所该拥有的权限
			List<ModuleCategory> moduleCateList=new ArrayList<ModuleCategory>();
            moduleList=powerInfoService.queryOpertorPowerList(merchant.getAccountNo(),"0");
			moduleCateList=powerInfoService.queryModuleCategoryList(oper,"0");
			
			
			getRequest().setAttribute("moduleList", moduleList);
			getRequest().setAttribute("moduleCateList", moduleCateList);
			getRequest().setAttribute("merchant",merchant);
			getRequest().setAttribute("accountNo", merchant.getAccountNo());
			
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}
	
	
	/**
	 * 设置业务分析系统的权限
	 * */
	@Action(value = "editMerchantAnalyPowerYJ", results = { @Result(name = "success", location = "/pages/operator/operator_power.jsp")
    })
	//修改操作员权限
	public String editMerchantAnalyPowerAction() throws Exception{
			//获取操作员的ID
			String accountNo=merchant.getAccountNo();
			//获取操作员新的权限
			String check=getRequest().getParameter("checkList");
			String[] list=null;
			if(null != check && !"".equals(check)){
				list=check.split(",");
			}
			
			//调用service层
			try {
				Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
				powerInfoService.editUpdateOperatorPowerService(accountNo,logingMerchant.getAccountNo(),list,"0");
				logger.info("------------------------------修改操作员权限成功！-----------------------------------");
			} catch (ServiceException e) {
				logger.info("------------------------------修改操作员权限失败！-----------------------------------");
				logger.error(e.getMessage(),e);
				return ERROR;
			}
			getRequest().setAttribute("msg","权限设置成功！");
			return queryMerchantListAction();
	}
	
	
	@Action(value = "editMerchantPowerYJ", results = { @Result(name = "success", location = "/pages/operator/operator_power.jsp")
             })
	//修改操作员权限
	public String editMerchantPowerAction() throws Exception{
				//获取操作员的ID
				String accountNo=merchant.getAccountNo();
				//获取操作员新的权限
				String check=getRequest().getParameter("checkList");
				String[] list=null;
				if(null != check && !"".equals(check)){
					list=check.split(",");
				}
				
				//调用service层
				try {
					Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
					powerInfoService.editUpdateOperatorPowerService(accountNo,logingMerchant.getAccountNo(),list,null);
					logger.info("------------------------------修改操作员权限成功！-----------------------------------");
				} catch (ServiceException e) {
					logger.info("------------------------------修改操作员权限失败！-----------------------------------");
					logger.error(e.getMessage(),e);
					return ERROR;
				}
				getRequest().setAttribute("msg","权限设置成功！");
				return queryMerchantListAction();
	}
	
	//查询机构
	public void org() throws Exception{
		Operators logingOperators = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		
		    List orgList=new ArrayList();
					
		    orgList=orgService.queryOrgList();
			getRequest().setAttribute("orgList", orgList);
			
			Map<String, String> merLevels=ConfigProperties.getAgentTypeProperties();
			getRequest().setAttribute("merLevels", merLevels);
			
			//查询角色类型
			Map<String, String> roleMap=ConfigProperties.getRoleTypeProperties();
			roleMap.remove(Role.MANAGER.getCode());
			roleMap.remove(Role.MARKET_DIRECT.getCode());
			roleMap.remove(Role.MARKET_LEAD.getCode());
			roleMap.remove(Role.FINANCE_COMM.getCode());
			roleMap.remove(Role.FINANCE_LEAD.getCode());
			roleMap.remove(Role.OPERATORS_LEAD.getCode());
			roleMap.remove(Role.SFB_AGENT.getCode());
			roleMap.remove(Role.MERCHANT.getCode());
			if(Role.O_MANAGER.getCode().equals(logingOperators.getRoleType())){
				roleMap.clear();
				roleMap.put(Role.O_MANAGER.getCode(), Role.O_MANAGER.getName());
				roleMap.put(Role.AGENT_BUSS.getCode(), Role.AGENT_BUSS.getName());
				roleMap.put(Role.AGENT.getCode(), Role.AGENT.getName());
				roleMap.put(Role.OPERATORS_COMM.getCode(), Role.OPERATORS_COMM.getName());
			}else if(Role.MANAGER.getCode().equals(logingOperators.getRoleType())){
				roleMap.remove(Role.SYSTEM.getCode());
				roleMap.remove(Role.MANAGER.getCode());
			}else if(Role.AGENT.getCode().equals(logingOperators.getRoleType())){
				roleMap.clear();
				roleMap.put(Role.AGENT_BUSS.getCode(), Role.AGENT_BUSS.getName());
				roleMap.put(Role.AGENT.getCode(), Role.AGENT.getName());
			}else if(Role.OPERATORS_COMM.getCode().equals(logingOperators.getRoleType())||Role.OPERATORS_LEAD.getCode().equals(logingOperators.getRoleType())){
				if(!"48502000".equals(logingOperators.getOneagentid())){
					roleMap.clear();
					roleMap.put(Role.AGENT_BUSS.getCode(), Role.AGENT_BUSS.getName());
					roleMap.put(Role.AGENT.getCode(), Role.AGENT.getName());
				}
			}
			roleList=roleMap;
			getRequest().setAttribute("roleList", roleMap);
			getRequest().setAttribute("roleType", logingOperators.getRoleType());
	}
	
	
	@Action(value = "szModelPower", results = { @Result(name = "success", location = "/pages/operator/operator_model.jsp"),
			@Result(type="chain", name = "input", location = "search")
    })
	public String szModelPower(){
       
		Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		//查询操作员所拥有的权限
		List<MerchantModuleRight> moduleList=new ArrayList<MerchantModuleRight>();
		
		//查询该操作员所该拥有的权限
		List<ModuleCategory> moduleCateList=new ArrayList<ModuleCategory>();
		if(merchant==null){
			addActionMessage("请选择一个代理商进行权限设置");
			return INPUT;
		}
		try{
            moduleList=powerInfoService.queryOpertorPowerList(merchant.getAccountNo(),null);
			moduleCateList=powerInfoService.queryModuleCategoryList(logingOperators,null);
			
			merchant=merchantServices.findMerchantByNo(merchant.getAccountNo());
			merchant.setRoleName(ConfigProperties.getRoleType(merchant.getRoleType()));	
			
			modelRsList=modelService.listAllProfitModelHeads(logingOperators);
			
			getRequest().setAttribute("moduleList", moduleList);
			getRequest().setAttribute("moduleCateList", moduleCateList);
			getRequest().setAttribute("merchant",merchant);
			getRequest().setAttribute("accountNo", merchant.getAccountNo());
			
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}
	
	
	
	
	
	
	@Action(value = "queryModel", results = { @Result(name = "success", location = "/pages/operator/operator_model.jsp")
    })
	public String queryModel(){
        Operators logingOperators=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		List<PowerModule> moduleList=new ArrayList<PowerModule>();
		
		List<ModuleCategory> moduleCateList=new ArrayList<ModuleCategory>();
		try{
		    moduleList=modelService.queryModule(logingOperators.getId(), modelHead.getModelCode());
		   	moduleCateList=powerInfoService.queryModuleCategoryList(logingOperators,null);
				
			merchant=merchantServices.findMerchantByNo(merchant.getAccountNo());
			merchant.setRoleName(ConfigProperties.getRoleType(merchant.getRoleType()));	
				
			modelRsList=modelService.listAllProfitModelHeads(logingOperators);
			
			getRequest().setAttribute("moduleList", moduleList);
			getRequest().setAttribute("moduleCateList", moduleCateList);
			getRequest().setAttribute("merchant",merchant);
			getRequest().setAttribute("accountNo", merchant.getAccountNo());
			
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}
	
	
	@Action(value = "saveByModel", results = { @Result(name = "success", location = "/pages/operator/operator_power.jsp")
    })
	public String saveByModel() throws Exception{
		String accountNo=merchant.getAccountNo();
		//获取操作员新的权限
		String check=getRequest().getParameter("checkList");
		String[] list=null;
		list=check.split(",");
		
		//调用service层
		try {
			Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			powerInfoService.editUpdateOperatorPowerService(accountNo,logingMerchant.getAccountNo(),list,null);
			logger.info("------------------------------修改操作员权限成功！-----------------------------------");
		} catch (ServiceException e) {
			logger.info("------------------------------修改操作员权限失败！-----------------------------------");
			logger.error(e.getMessage(),e);
			return ERROR;
		}
		getRequest().setAttribute("msg","权限设置成功！");
		return queryMerchantListAction();
	}
	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSession()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (PowerInfoSearchCondition)getSession().getAttribute(SEARCH_SESSION_BEAN_MERCHANT_POWER_YJ);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSubClass()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchConditionToSubClass(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	/* (non-Javadoc)
	 * @see com.roc.page.PaginationBaseAction#setSearchToConditionSession(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_MERCHANT_POWER_YJ, searchCondition);
	}

	public PowerInfoSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(PowerInfoSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public Operators getMerchant() {
		return merchant;
	}

	public void setMerchant(Operators merchant) {
		this.merchant = merchant;
	}

	public List<Object> getModelRsList() {
		return modelRsList;
	}

	public void setModelRsList(List<Object> modelRsList) {
		this.modelRsList = modelRsList;
	}

	public PowerModel getModelHead() {
		return modelHead;
	}

	public void setModelHead(PowerModel modelHead) {
		this.modelHead = modelHead;
	}

	public Map<String, String> getRoleList() {
		return roleList;
	}

	public void setRoleList(Map<String, String> roleList) {
		this.roleList = roleList;
	}


}
